<template>
	<div class="trtc-container">
		<image :src="data.avatar" mode="widthFix"></image>
		<p>{{data.realname}}</p>
		<span v-if="state==1">正在等待对方接听</span>
		<span v-if="state==2">邀请你语音通话</span>
		<span v-if="state==3">通话中</span>
		<span v-if="state==4">{{finish}}</span>
		<footer v-if="state!=4">
			<!-- <view v-if="state==3" :class="{'marginRight2':state==3}">
				<image v-if="mute" src="../../static/image/contacts/11.png" mode="widthFix"></image>
				<image v-else src="../../static/image/contacts/13.png" mode="widthFix"></image>
				静音
			</view> -->
			<!-- ,{'marginRight2':state==3} -->
			<view :class="[{'marginRight':state==2}]" @click="exitRoom">
				<image src="../../static/image/contacts/9.png" mode="widthFix"></image>
				{{state==1?'取消':'挂断'}}
			</view>
			<view v-if="state==2" @click="startLocalAudio">
				<image src="../../static/image/contacts/10.png" mode="widthFix"></image>
				接听
			</view>
			<!-- <view v-if="state==3">
				<image v-if="HF" src="../../static/image/contacts/12.png" mode="widthFix"></image>
				<image v-else src="../../static/image/contacts/14.png" mode="widthFix"></image>
				免提
			</view> -->
		</footer>
		<view class="message">
			<view id='root'>
				<trtc-local-view :viewId="userId"></trtc-local-view>
			</view>
			<view>
				<trtc-remote-view v-if="remoteUserId" :userId="remoteUserId" :viewId="remoteUserId">
				</trtc-remote-view>
			</view>
		</view>
	</div>
</template>

<script>
	import permision from "@/TrtcCloud/permission.js";
	import TrtcCloud from '@/TrtcCloud/lib/index';
	import {
		TRTCAppScene,
		TRTCAudioRoute,
		TRTCVideoStreamType
	} from '@/TrtcCloud/lib/TrtcDefines';
	import TrtcLocalView from '@/TrtcCloud/view/TrtcLocalView';
	import TrtcRemoteView from '@/TrtcCloud/view/TrtcRemoteView';
	import {
		useMsgStore
	} from '@/store/message';
	import pinia from '@/store/index'
	const msgStore = useMsgStore(pinia)

	const bgAudioManager = uni.getBackgroundAudioManager();

	export default {
		components: {
			TrtcLocalView,
			TrtcRemoteView,
		},
		data() {
			return {
				state: 1,
				mute: true,
				HF: true,
				trtcCloud: null,
				sdkAppId: 1600046845,
				userSig: '',
				roomId: 0,
				strRoomId: 0,
				userId: '',
				appScene: TRTCAppScene.TRTCAppSceneVideoCall,
				isFrontCamera: true,
				streamType: TRTCVideoStreamType.TRTCVideoStreamTypeBig,
				audioRoute: TRTCAudioRoute.TRTCAudioRouteSpeaker,
				remoteUserId: '',
				retreat: 1,
				id: '',
				play: false,
				finish: '通话已结束',
				data: {}, //对方数据
			}
		},
		onLoad(res) {
			this.data = msgStore.getContact(res.youID)
			let arr = [res.userId, res.youID]
			arr.sort((a, b) => a - b)
			this.strRoomId = arr[0] + '-' + arr[1]
			this.userId = res.userId

			// bgAudioManager.onPlay(() => {
			// 	console.log('播放回调', this.play)
			// 	// if (!this.play) {
			// 	// 	bgAudioManager.stop()
			// 	// }
			// })

			if (res.status == 2) {
				this.state = 2
				this.id = res.id
			}

			this.$httpRequest('/api/im/getUserSign').then(res => {
				this.userSig = res.data
				this.enterRoom()
			})
			uni.$emit('play', () => {
				console.log('后台运行')
				if (!this.play) {
					this.play = true
					bgAudioManager.src = 'https://ytw.hn8090kj.com/static/14060.mp3'
					bgAudioManager.play()
				}
			})

			uni.$off('webrtcConn');
			// 接收websocket传输过来的消息,并发送给webview
			uni.$on('webrtcConn', (e) => {
				if (e.extends.event == 'acceptRtc') {
					this.startLocalAudio()
				}
				if (e.extends.event == 'busy') {
					this.finish = '对方忙线中'
					this.status = 4
					this.play = false
					bgAudioManager.stop()
					setTimeout(() => {
						this.$method.retreat(1)
					}, 1000)
				}
			})
			if (res.status == 1) {
				this.id = this.$util.getUuid()
				// bgAudioManager.src = 'https://ytw.hn8090kj.com/static/14060.mp3'
				// bgAudioManager.play()
				// this.play=true
				this.$httpRequest('/api/im/sendToMsg', {
					toContactId: res.youID,
					event: 'calling',
					id: this.id,
					status: res.status,
					code: 901,
				})
			}
		},
		mounted() {
			if (uni.getSystemInfoSync().platform === 'android') {
				permision.requestAndroidPermission('android.permission.RECORD_AUDIO');
				permision.requestAndroidPermission('android.permission.CAMERA');
			}
		},
		unmounted() {
			this.handleUninstallEvents();
		},
		onUnload() {
			this.play = false
			this.exitRoom()
			this.exitRoom()
			bgAudioManager.stop()
			this.destroyInstance();
		},
		onBackPress() {
			this.play = false
			this.exitRoom()
			bgAudioManager.stop()
			this.destroyInstance();
		},
		beforeUnmount() {

		},
		methods: {
			destroyInstance() {
				if (this.trtcCloud) {
					TrtcCloud.destroyInstance();
					this.trtcCloud = null;
				}
			},
			createTrtcCloud() {
				this.trtcCloud = TrtcCloud.createInstance();
				this.handleEvents();
			},
			enterRoom() {
				try {
					// 【1】创建实例
					this.createTrtcCloud();
					// 【2】进房
					const {
						roomId,
						userId,
						sdkAppId,
						appScene,
						userSig,
						strRoomId
					} = this;
					let param = {
						roomId: 0,
						userId,
						sdkAppId,
						userSig,
						strRoomId
					};
					if (!this.play) {
						if (!this.play) {
							this.play = true
							bgAudioManager.src = 'https://ytw.hn8090kj.com/static/14060.mp3'
							bgAudioManager.play()
						}
					}
					this.trtcCloud.enterRoom(param, appScene);

					// uni.showToast({
					// 	title: 'enterRoom ',
					// 	icon: 'none',
					// });
				} catch (error) {
					console.log(`enterRoom error = ${JSON.stringify(error)}`);
				}
			},
			exitRoom() {
				if (this.state == 4) {
					return
				}
				let code = this.state == 3 ? 906 : this.state == 2 ? 903 : 902
				// uni.showToast({
				// 	title: JSON.stringify({
				// 		toContactId: this.data.user_id,
				// 		event: 'hangup',
				// 		id: this.id,
				// 		code: code,
				// 	}),
				// 	icon: 'none',
				// });
				this.state = 4
				this.$httpRequest('/api/im/sendToMsg', {
					toContactId: this.data.user_id,
					event: 'hangup',
					id: this.id,
					code: code,
				})
				try {
					this.stopLocalAudio();
					this.trtcCloud.exitRoom();
					this.remoteUserId = '';
				} catch (e) {

				}
			},
			// 开启关闭静音
			muteLocalAudio() {
				this.trtcCloud.muteLocalAudio();
			},
			// 开启本地音频采集和上行
			startLocalAudio() {
				this.play = false
				bgAudioManager.stop()
				this.trtcCloud.enableAudioVolumeEvaluation(300);
				this.trtcCloud.startLocalAudio();
				if (this.state == 2) {
					this.$httpRequest('/api/im/sendToMsg', {
						toContactId: this.data.user_id,
						event: 'acceptRtc',
						id: this.id,
						status: 2,
						code: 901,
					})
				}
				this.state = 3
			},
			// 关闭本地音频采集和上行
			stopLocalAudio() {
				this.trtcCloud.stopLocalAudio();
			},
			handleEvents() {
				this.trtcCloud.on('onWarning', (res) => {
					console.log(`onWarning: ${JSON.stringify(res)}`);
				});
				this.trtcCloud.on('onError', (res) => {
					console.log(`error: ${JSON.stringify(res)}`);
				});
				this.trtcCloud.on('onEnterRoom', (result) => {
					console.log(`- onEnterRoom = ${result}`);
					if (result > 0) {} else {
						console.log(`enter room failed，error code = ${result}`);
					}
				});
				this.trtcCloud.on('onExitRoom', (reason) => {
					const reasonList = ['已挂断', '被服务器踢出当前房间', '当前通话已结束'];
					this.finish = reasonList[reason]
					this.state = 4
					this.play = false
					bgAudioManager.stop()
					setTimeout(() => {
						if (this.retreat == 1) {
							this.retreat = 2
							this.$method.retreat(1)
						}
					}, 1000)

				});
				this.trtcCloud.on('onFirstVideoFrame', (res) => {
					// console.log(`渲染的首帧画面响应 = ${JSON.stringify(res)}`);
				});
				this.trtcCloud.on('onRemoteUserEnterRoom', (userId) => {
					this.remoteUserId = userId;
				});
				this.trtcCloud.on('onRemoteUserLeaveRoom', (userId) => {
					this.finish = '当前通话已结束'
					this.state = 4
					this.play = false
					bgAudioManager.stop()
					setTimeout(() => {
						if (this.retreat == 1) {
							this.retreat = 2
							this.$method.retreat(1)
						}
					}, 1000)
				});
				this.trtcCloud.on('onUserVideoAvailable', (res) => {
					const {
						userId,
						available
					} = res;
					if (userId && available) {
						this.remoteUserId = userId;
						this.trtcCloud.startRemoteView(this.remoteUserId, this.streamType, this.remoteUserId);
					}
				});
				this.trtcCloud.on('onUserVoiceVolume', (res) => {
					// res.userVolumes.forEach(val => {
					// 	if (val.userId == this.userId) {
					// 		console.log('自己音量 = ', res);
					// 	}else{
					// 		console.log('对方音量 = ', res);
					// 	}
					// })
				});
			},
			handleUninstallEvents() {
				this.trtcCloud.off('*');
			}
		}
	}
</script>

<style lang="scss">
	.trtc-container {
		width: 100vw;
		height: 100vh;
		background-color: #000000;
		display: flex;
		flex-direction: column;
		align-items: center;
		position: relative;

		&>footer {
			width: 690rpx;
			display: flex;
			justify-content: center;
			position: absolute;
			bottom: 12.5vh;

			&>.marginRight {
				margin-right: 234rpx;
			}

			&>.marginRight2 {
				margin-right: 130rpx;
			}

			&>view {
				display: flex;
				align-items: center;
				flex-direction: column;
				color: #fff;
				font-size: 30rpx;

				&>image {
					width: 112rpx;
					margin-bottom: 12rpx;
				}
			}
		}

		&>span {
			color: #CACACA;
			height: 32rpx;
			line-height: 32rpx;
			font-size: 32rpx;
			margin-top: 15vh;
		}

		&>p {
			font-size: 40rpx;
			color: #fff;
			margin-top: 30rpx;
		}

		&>image {
			width: 154rpx;
			height: 154rpx;
			margin-top: 15vh;
			border-radius: 50%;
		}
	}
</style>